<template>
  <div class="my-dialog">
    <vxe-modal
      show-footer
      show-confirm-button
      show-cancel-button
      show-zoom
      title="地图标绘"
      resize
      :lock-view="false"
      :mask="false"
      v-model="visible"
      :width="350"
      :height="500"
      @close="handleClose"
      size="small"
      :position="{
        top: 40,
        left: 15,
      }"
    >
      <!-- 标绘工具栏 -->
      <!-- <div class="plot-toolbar">
        <div class="toolbar-item" @click="btnClick('loadFile')">
          <i class="iconfont icon-dakaiwenjian"></i>
          <span>打开</span>
        </div>
        <div class="toolbar-item" @click="btnClick('saveFile')">
          <i class="iconfont icon-baocun"></i>
          <span>保存</span>
        </div>
        <div class="toolbar-divider"></div>
        <div class="toolbar-item" @click="btnClick('plotDelete')">
          <i class="iconfont icon-shanchu"></i>
          <span>删除</span>
        </div>
        <div class="toolbar-item" @click="btnClick('plotEdit')">
          <i class="iconfont icon-shifoubianji"></i>
          <span>{{ editMode ? '关闭编辑' : '开启编辑' }}</span>
        </div>
      </div> -->

      <!-- 标绘类型选择 -->
      <div class="plot-type-select">
        <el-select
          v-model="plotInitValue"
          @change="onChangePlot"
          placeholder="请选择标绘类型"
        >
          <el-option
            v-for="(item, index) in plotTypeList"
            :key="index"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
      </div>

      <!-- 标绘工具列表 -->
      <div class="plot-tools">
        <div
          v-for="(item, index) in plotList"
          :key="index"
          class="plot-tool-item"
          :class="{ active: isPlotActive === index }"
          @click="onChangePlotType(index, item)"
        >
          <img :src="item.iconImg" alt="标绘图标" />
          <span>{{ item.name }}</span>
        </div>
      </div>

      <!-- 隐藏的文件输入框 -->
      <input
        type="file"
        accept=".json"
        style="display: none"
        id="plot-loadFile"
        @change="loadFileChange"
      />
    </vxe-modal>

    <!-- 标绘属性面板 -->
    <plot-style ref="plotStylePanel"></plot-style>
  </div>
</template>

<script>
import plotList from "./plotList.js";
import PlotStyle from "./plotStyle.vue";

// 地图标绘工具
window.plotDrawTool = undefined;
let nowPlotEntObj = undefined; // 当前编辑的对象

export default {
  name: "PlotPanel",
  components: {
    PlotStyle,
  },
  data() {
    return {
      visible: false,
      plotInitValue: "",
      isPlotActive: -1,
      plotTypeList: [], // 标绘类型
      plotList: [], // 标绘列表
      editMode: false, // 编辑模式
      cardDialog: false, // 是否打开弹窗
    };
  },
  mounted() {
    // 设置下拉框
    this.$set(this, "plotTypeList", Object.keys(plotList));
    this.$set(
      this,
      "plotInitValue",
      this.plotTypeList.length ? this.plotTypeList[0] : ""
    );
    this.$set(
      this,
      "plotList",
      this.plotTypeList.length ? plotList[this.plotTypeList[0]] : []
    );

    // 初始化标绘工具
    this.initPlotTool();
  },
  beforeDestroy() {
    if (window.plotDrawTool) {
      window.plotDrawTool.destroy();
      window.plotDrawTool = undefined;
    }
    this.closePlotStyle();
  },
  methods: {
    open() {
      this.visible = true;
      // 重新初始化标绘工具
      this.initPlotTool();
    },
    handleClose() {
      this.visible = false;
      this.closePlotStyle();
      this.$emit("menuClose", "plotPanelRef");
    },
    // 关闭样式面板
    closePlotStyle() {
      this.$refs.plotStylePanel.handleClose();
    },
    // 打开样式面板
    openPlotStyle(entObj) {
      this.$refs.plotStylePanel.open(entObj);
    },
    initPlotTool() {
      if (!window.plotDrawTool && window.viewer) {
        window.plotDrawTool = new window.vis3d.plot.Tool(window.viewer, {
          canEdit: true,
        });

        let that = this;
        window.plotDrawTool.on("endCreate", function (entObj, ent) {
          // 创建完成后
          nowPlotEntObj = entObj;
          that.isPlotActive = -1;
          that.openPlotStyle(entObj);
          let positions = entObj.getPositions(true);
          console.log("plot positions-->", JSON.stringify(positions));
        });

        window.plotDrawTool.on("startEdit", function (entObj, ent) {
          // 开始编辑
          nowPlotEntObj = entObj;
          that.openPlotStyle(entObj);
        });

        window.plotDrawTool.on("endEdit", function (entObj, ent) {
          // 编辑完成后
          nowPlotEntObj = undefined;
          that.closePlotStyle();
        });

        // 添加双击事件监听
        window.plotDrawTool.on("dbClick", function (entObj, ent) {
          // 双击实体时打开属性面板
          nowPlotEntObj = entObj;
          that.openPlotStyle(entObj);
        });

        // 监听删除事件
        window.plotDrawTool.on("remove", function (entObj) {
          // 如果删除的是当前编辑的实体，则关闭属性面板
          if (nowPlotEntObj && nowPlotEntObj.id === entObj.id) {
            that.$refs.plotStylePanel.handleClose();
            nowPlotEntObj = undefined;
          }
        });

        // // 使用viewer监听右键事件
        // window.viewer.screenSpaceEventHandler.setInputAction(function(event) {
        //   const pickedObject = window.viewer.scene.pick(event.position);
        //   if (pickedObject && pickedObject.id) {
        //     if (!hasDeleteButton) {
        //       hasDeleteButton = true;
        //     } else {
        //       // 使用vis3d的方式阻止右键菜单
        //     }
        //   }
        // }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
        // 右键监听逻辑
        window.viewer.screenSpaceEventHandler.setInputAction(function (event) {
          // 每次右键前，主动移除已有的删除按钮
          const existingDeleteBtn = document.getElementById("vis3d-plot-delete");
          if (existingDeleteBtn) {
            existingDeleteBtn.remove();
          }

          const pickedObject = window.viewer.scene.pick(event.position);
          if (pickedObject && pickedObject.id) {
            // 让 vis3d 正常处理右键事件，创建新的删除按钮
          }
        }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
      }
    },
    // 选择标绘类型
    onChangePlot(data) {
      this.$set(this, "plotList", plotList[data]);
      this.$set(this, "isPlotActive", -1);
    },
    // 选择绘制样式
    onChangePlotType(index, item) {
      this.$set(this, "isPlotActive", index);
      this.startDraw(item);
    },
    // 绘制
    startDraw(item) {
      if (!window.plotDrawTool) {
        this.initPlotTool();
      }
      if (!window.plotDrawTool) return;

      // 确保item是深拷贝
      item = JSON.parse(JSON.stringify(item));

      // 设置默认样式
      if (!item.style) {
        item.style = {
          color: "#4c8f67",
          outline: true,
          outlineColor: "#ff0000",
          heightReference: 1,
        };
      }

      // 开始绘制
      window.plotDrawTool.start(item);
      this.$set(this, "cardDialog", true);
    },
    // 工具栏按钮点击
    btnClick(type) {
      if (!window.plotDrawTool) {
        this.initPlotTool();
      }
      if (!window.plotDrawTool) return;

      if (type === "loadFile") {
        let dom = document.getElementById("plot-loadFile");
        if (dom) dom.click();
      }

      if (type === "saveFile") {
        let jsondata = window.plotDrawTool.toGeojson();
        if (!jsondata) return;
        window.vis3d.tool.downloadFile(
          "图上标绘.json",
          JSON.stringify(jsondata)
        );
      }

      if (type === "plotDelete") {
        window.plotDrawTool.removeAll();
      }

      if (type === "plotEdit") {
        this.editMode = !this.editMode;
        if (this.editMode) {
          window.plotDrawTool.openEdit();
        } else {
          window.plotDrawTool.closeEdit();
        }
      }
    },
    // 加载文件
    loadFileChange(e) {
      if (!window.plotDrawTool) {
        this.initPlotTool();
      }
      if (!window.plotDrawTool) return;

      let file = e.target.files[0];
      let fileName = file.name;
      let fileType = fileName
        .substring(fileName.lastIndexOf(".") + 1, fileName.length)
        .toLowerCase();
      if (fileType != "json") {
        console.warn("文件类型不合法,请选择json格式标注文件！");
        return;
      }
      if (window.FileReader) {
        let reader = new FileReader();
        reader.readAsText(file, "UTF-8");
        reader.onloadend = function (e) {
          let strjson = this.result;
          strjson = JSON.parse(strjson);
          window.plotDrawTool.createByGeojson(strjson);
        };
      }
      e.target.value = "";
    },
    // 设置实体样式
    setEntityStyle(style) {
      if (!window.plotDrawTool) return;
      window.plotDrawTool.updateOneStyle(nowPlotEntObj, style);
    },
  },
};
</script>

<style scoped lang="scss">
.plot-toolbar {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #dcdfe6;

  .toolbar-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 60px;
    height: 60px;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      background-color: #ecf5ff;
    }

    i {
      font-size: 24px;
      margin-bottom: 5px;
    }

    span {
      font-size: 12px;
    }
  }

  .toolbar-divider {
    width: 1px;
    height: 30px;
    background-color: #dcdfe6;
    margin: 0 10px;
  }
}

.plot-type-select {
  padding: 10px;

  .el-select {
    width: 100%;
  }
}

.plot-tools {
  display: flex;
  flex-wrap: wrap;
  padding: 10px;

  .plot-tool-item {
    width: 90px;
    height: 90px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin: 0 10px 10px 0;
    cursor: pointer;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    transition: all 0.3s;

    &:hover {
      border-color: #409eff;
    }

    &.active {
      border-color: #409eff;
      background-color: #ecf5ff;
    }

    img {
      width: 40px;
      height: 40px;
      margin-bottom: 5px;
    }

    span {
      font-size: 12px;
      text-align: center;
    }
  }
}
</style>
